import './index.css'
import React, { useRef } from 'react';
import { connect, useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, message } from 'antd';
import http from '../../api'
import { setUserInfo } from '../../redux/userInfoRedux/actions'
// 导入粒子效果相关组件
import { useCallback } from "react";
import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";

function Login() {
  const history = useHistory()
  const formRef = useRef()
  const dispatch = useDispatch()

  // 初始化粒子效果
  const particlesInit = useCallback(async engine => {
    await loadFull(engine);
  }, []);

  // 粒子加载完成回调
  const particlesLoaded = useCallback(async container => {
    // console.log(container);
  }, []);

  const onFinish = () => {
    formRef.current.validateFields().then(res => {
      getLoginInfo(res)
    }).catch(err => {
      console.log(err)
    })
  };

  //获取登录用户信息 需要同时获取登录用户的角色信息并且token存一份 redux存一份 
  const getLoginInfo = async (user) => {
    try {
      const res = await http.get(`/users?username=${user.username}&password=${user.password}`)
      const userRoleInfo = await http.get(`/roles?id=${String(res.data[0].roleId)}`)
      const { data } = res
      if (data && data.length == 1) {
        const userInfo = {
          ...data[0],
          role: userRoleInfo.data[0]
        }
        const uInfo = JSON.stringify(userInfo)
        localStorage.setItem('token', uInfo)
        //全局store存储
        dispatch(setUserInfo(userInfo))
        history.push('/home')
        formRef.current.setFieldValue({})
        formRef.current.resetFields()
        message.error('登录成功')
      } else {
        message.error('用户名或密码错误')
      }
    } catch {

    }
  }

  return (
    <div className='login'>
      <Particles
        id="tsparticles"
        init={particlesInit}
        loaded={particlesLoaded}
        options={{
          background: {
            color: {
              value: "#0d47a1",
            },
          },
          fpsLimit: 120,
          interactivity: {
            events: {
              onClick: {
                enable: true,
                mode: "push",
              },
              onHover: {
                enable: true,
                mode: "repulse",
              },
              resize: true,
            },
            modes: {
              push: {
                quantity: 4,
              },
              repulse: {
                distance: 200,
                duration: 0.4,
              },
            },
          },
          particles: {
            color: {
              value: "#ffffff",
            },
            links: {
              color: "#ffffff",
              distance: 150,
              enable: true,
              opacity: 0.5,
              width: 1,
            },
            collisions: {
              enable: true,
            },
            move: {
              direction: "none",
              enable: true,
              outModes: {
                default: "bounce",
              },
              random: false,
              speed: 3,
              straight: false,
            },
            number: {
              density: {
                enable: true,
                area: 800,
              },
              value: 80,
            },
            opacity: {
              value: 0.5,
            },
            shape: {
              type: "circle",
            },
            size: {
              value: { min: 1, max: 5 },
            },
          },
          detectRetina: true,
        }}
      />
      <div className='loginBox'>
        <div className='title'>全球新闻发布管理系统</div>
        <Form
          ref={formRef}
          name="normal_login"
          className="login-form"
          initialValues={{ remember: true }}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: 'Please input your Username!' }]}
          >
            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: 'Please input your Password!' }]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" className="login-form-button" onClick={onFinish}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
};

export default connect(
  state => ({
    userInfo: state.UserInfo
  }),
  {
    setUserInfo: setUserInfo
  }
)(Login)
